package com.lxl.bt.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lxl.bt.R;
import com.lxl.bt.activity.BaseFragment;
import com.lxl.bt.activity.OrderDetailActivity;
import com.lxl.bt.adapter.OrderItemAdapter;
import com.lxl.bt.bean.OrderListResult;
import com.lxl.bt.databinding.FragmentOrderlistBinding;
import com.lxl.bt.net.NetApi;
import com.lxl.bt.net.Result;
import com.lxl.bt.retorfit.NetCallback;
import com.lxl.bt.retorfit.RetrofitUtil;
import com.lxl.bt.util.ACache;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.lxl.bt.util.PickViewUtil.createPickView;
import static com.lxl.bt.util.TimeUtil.FORMAT_OTHER_YEAR;

/**
 * Create by lvxinlong
 * on 分类宣传
 * on 2020年5月9日15:32:57
 **/
public class OrderListFragment extends BaseFragment {


    @BindView(R.id.ll1_1)
    LinearLayout ll11;
    @BindView(R.id.ll1_2)
    LinearLayout ll12;
    @BindView(R.id.rcv)
    RecyclerView rcv;
    private Unbinder unbinder;
    ACache aCache;
    private BaseQuickAdapter<OrderListResult.OrderListItem, BaseViewHolder> promoAdapter;
    String coinName;
    List<OrderListResult.OrderListItem> promoItems = new ArrayList<>();
    private FragmentOrderlistBinding bind;
    private String[] productOptions = {"全部", "算力", "矿机"};
    private String[] productOptionsValues = {"", "0", "1"};

    private String[] statusOptions = {"全部", "挖矿中", "已结束"};
    private String[] statusOptionsValues = {"", "1", "2"};

    private String[] modeOptions = {"全部", "正常模式"};
    private String[] modeOptionsValues = {"", ""};

    private int productIndex, modeIndex, statusIndex;
    private String type = "", modeValue = "", countStatus = "";
    private int page = 0, size = 10;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FORMAT_OTHER_YEAR);

    public static OrderListFragment newInstance(String title) {
        Bundle bundle = new Bundle();
        OrderListFragment fragment = new OrderListFragment();
        bundle.putSerializable("data", title);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            coinName = getArguments().getString("data");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_orderlist, container, false);
//        ((BaseActivity) getActivity()).setStatusBarFullTransparent();
        bind = DataBindingUtil.bind(view);
        //返回一个Unbinder值（进行解绑），注意这里的this不能使用getActivity()
        unbinder = ButterKnife.bind(this, view);
//        EventBus.getDefault().register(this);
        aCache = ACache.get(getActivity());
        promoAdapter = new BaseQuickAdapter<OrderListResult.OrderListItem, BaseViewHolder>(R.layout.item_orderitem) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, OrderListResult.OrderListItem item) {

            }

            @Override
            public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
                OrderListResult.OrderListItem item = getItem(position);
                holder.setText(R.id.tvName, item.productName);
                holder.setText(R.id.tvTime, item.createTime);
                holder.setText(R.id.tvDes, item.orderNo);
                holder.setText(R.id.tv10, item.power);
                holder.setText(R.id.tvStatus, item.getPayStatusText());
                holder.setText(R.id.tvT1, item.payPrice);
                holder.setText(R.id.tvLeiji, item.totalOut);
                holder.setText(R.id.tvZt, item.yesOut);
                holder.setText(R.id.tvEndDay, "挖矿剩余 " + item.userDays + " 天");
                String start = simpleDateFormat.format(item.countStartDate);
                String end = simpleDateFormat.format(item.countEndDate);
                holder.setText(R.id.tvEndTime, start + " - " + end);
            }
        };
//        rcv.addItemDecoration(new MyDividerDecoration(getResources().getColor(R.color.transparent), 2));
//        rcv.setLayoutManager(new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        rcv.setAdapter(promoAdapter);
        initView();
        return view;
    }

    private void initView() {
        bind.tvProduct.setOnClickListener(v -> createPickView(getActivity(), (options1, options2, options3, view) -> {
            this.productIndex = options1;
            bind.tvProduct.setText(productOptions[productIndex]);
            type = productOptionsValues[productIndex];
            refresh();
        }, "产品", productOptions, productIndex));

        bind.tvStatus.setOnClickListener(v -> createPickView(getActivity(), (options1, options2, options3, view) -> {
            this.statusIndex = options1;
            bind.tvStatus.setText(statusOptions[statusIndex]);
            countStatus = statusOptionsValues[statusIndex];
            refresh();
        }, "状态", statusOptions, statusIndex));

        bind.tvMode.setOnClickListener(v -> createPickView(getActivity(), (options1, options2, options3, view) -> {
            this.modeIndex = options1;
            bind.tvMode.setText(modeOptions[modeIndex]);
            modeValue = modeOptionsValues[modeIndex];
            refresh();
        }, "模式", modeOptions, modeIndex));
        bind.refreshLayout.setEnableLoadMore(true);
        bind.refreshLayout.setEnableRefresh(true);
        bind.refreshLayout.setOnRefreshListener(refreshLayout -> {
            refresh();
        });
        bind.refreshLayout.setOnLoadMoreListener(refreshLayout -> getData());
    }

    private void refresh() {
        page = 0;
        getData();
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void getData() {
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .queryOrders(coinName.toLowerCase(), countStatus, type, page, size, new ArrayList<>())
                .enqueue(new NetCallback<Result<OrderListResult>>() {
                    @Override
                    public void onSuccess(Result<OrderListResult> result) {
                        List<OrderListResult.OrderListItem> content = result.getData().content;
                        if (page == 0) {
                            promoAdapter.setNewData(content);
                        } else {
                            promoAdapter.addData(content);
                        }
                        bind.refreshLayout.setEnableLoadMore(result.getData().totalElements > promoAdapter.getData().size() ? true : false);
                        page++;
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        bind.refreshLayout.finishLoadMore();
                        bind.refreshLayout.finishRefresh();
                    }

                    @Override
                    public void netLogin() {

                    }
                });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }


//    @Subscribe
//    public void onEventMainThread(EventTagBean event) {
//    }

    /**
     * onDestroyView中进行解绑操作
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

    }

}
